<template>
  <el-main>
    <el-form
      ref="searchForm"
      :model="parms"
      label-width="80px"
      :inline="true"
      size="small"
    >
      <el-form-item label="角色名称">
        <el-input v-model="parms.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="searchBtn">查询</el-button>
        <el-button
          style="color: #ff7670"
          icon="el-icon-delete"
          @click="resetBtn"
        >重置</el-button>
        <el-button v-if="hasPerm('sys:role:add')" type="primary" icon="el-icon-plus" @click="addBtn">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 角色列表 -->
    <el-table
      :data="roleList"
      :height="tableHeight"
      size="small"
      empty-text="暂无数据"
      border
      stripe
    >
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column align="center" width="290" label="操作">
        <template slot-scope="scope">
          <el-button v-if="hasPerm('sys:role:edit')" type="primary" icon="el-icon-edit" size="small" @click="editBtn(scope.row)">编辑</el-button>
          <el-button v-if="hasPerm('sys:role:assignMenu')" type="primary" icon="el-icon-edit" size="small" @click="assignRoleBtn(scope.row)">分配权限</el-button>
          <el-button v-if="hasPerm('sys:role:delete')" type="danger" icon="el-icon-delete" size="small" @click="deleteBtn(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page.sync="parms.curentPage"
      :page-sizes="[10, 20, 40, 80, 100]"
      :page-size="parms.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="parms.total"
      background
      @size-change="sizeChange"
      @current-change="currentChange"
    />
    <!-- 新增编辑弹框 -->
    <sys-dialog
      :title="dialog.title"
      :visible="dialog.visible"
      :height="dialog.height"
      :width="dialog.width"
      @onClose="onClose"
      @onConfirm="onConfirm"
    >
      <div slot="content">
        <el-form
          ref="addForm"
          :model="addModel"
          :rules="rules"
          :inline="true"
          label-width="85px"
          size="small"
        >
          <el-form-item prop="roleName" style="width: 280px" label="角色名称:">
            <el-input v-model="addModel.roleName" />
          </el-form-item>
          <el-form-item style="width: 280px" label="角色描述:">
            <el-input v-model="addModel.remark" />
          </el-form-item>
        </el-form>
      </div>
    </sys-dialog>
    <!-- 分配权限弹框 -->
    <sys-dialog
      :title="assignDialog.title"
      :height="assignDialog.height"
      :width="assignDialog.width"
      :visible="assignDialog.visible"
      @onClose="assignClose"
      @onConfirm="assignConfirm"
    >
      <template slot="content">
        <span>
          <el-tree
            ref="assignTree"
            default-expand-all
            :default-checked-keys="assignTreeChecked"
            :data="assignTreeData"
            node-key="menuId"
            :props="defaultProps"
            empty-text="暂无数据"
            :show-checkbox="true"
          />
        </span>
      </template>
    </sys-dialog>
  </el-main>
</template>

<script>
import { getRoleListApi, addRoleApi, editRoleApi, deleteRoleApi, getAssignTreeApi, assignSaveApi } from '@/api/role'
import { getUserId } from '@/utils/auth'
import SysDialog from '@/components/system/SysDialog'
export default {
  // 注册组件
  components: {
    SysDialog
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'menuLabel'
      },
      // 角色id
      roleId: '',
      // 分配权限树数据
      assignTreeData: [],
      // 树默认选中的节点
      assignTreeChecked: [],
      // 分配权限弹框属性
      assignDialog: {
        title: '',
        width: 300,
        height: 500,
        visible: false
      },
      // 表单验证规则
      rules: {
        roleName: [{
          required: true,
          trigger: 'blur',
          message: '请填写角色名称'
        }]
      },
      // 新增或编辑数据域
      addModel: {
        type: '', // 0：新增 1 添加
        roleId: '',
        roleName: '',
        remark: ''
      },
      // 弹框属性
      dialog: {
        title: '',
        height: 150,
        width: 610,
        visible: false
      },
      // 页面高度
      tableHeight: 0,
      // 表格数据
      roleList: [],
      // 角色搜索框的数据绑定
      parms: {
        pageSize: 10, // 每页显示几条数据
        currentPage: 1, // 当前第几页
        roleName: '', // 角色名
        total: 0 // 总条数
      }
    }
  },
  created() {
    this.getRoleList()
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 210
    })
  },
  methods: {
    // 分配权限确认
    async assignConfirm() {
      // 获取选中的节点id
      const ids = this.$refs.assignTree.getCheckedKeys().concat(this.$refs.assignTree.getHalfCheckedKeys())
      console.log(ids)
      if (ids.length === 0) {
        this.$message.warning('请勾选权限!')
        return
      }
      const parm = {
        roleId: this.roleId,
        list: ids
      }
      const res = await assignSaveApi(parm)
      console.log(res)
      if (res && res.code === 200) {
        this.assignDialog.visible = false
        this.$message.success(res.msg)
      }
    },
    // 分配权限取消
    assignClose() {
      this.assignDialog.visible = false
    },
    // 分配权限按钮
    async assignRoleBtn(row) {
      this.assignTreeData = []
      this.assignTreeChecked = []
      this.roleId = row.roleId
      this.assignDialog.title = '为【' + row.roleName + '】分配权限'
      this.assignDialog.visible = true
      const parm = {
        userId: getUserId(),
        roleId: row.roleId
      }
      const res = await getAssignTreeApi(parm)
      if (res && res.code === 200) {
        console.log(res)
        // 赋值
        this.assignTreeData = res.extend.list.listmenu
        this.assignTreeChecked = res.extend.list.checkList
        console.log(this.assignTreeChecked)
      }
      if (this.assignTreeChecked.length > 0) {
        const newArr = []
        this.assignTreeChecked.forEach((item) => {
          this.checked(item, this.assignTreeData, newArr)
        })
        this.assignTreeChecked = newArr
        console.log(newArr)
      }
    },
    checked(id, data, newArr) {
      data.forEach((item) => {
        if (item.menuId === id) {
          if (item.children && item.children.length === 0) {
            newArr.push(item.menuId)
          }
        } else {
          if (item.children != null && item.children.length !== 0) {
            this.checked(id, item.children, newArr)
          }
        }
      })
    },
    // 删除按钮
    async deleteBtn(row) {
      const confirm = await this.$myconfirm('确定删除该数据吗?')
      console.log(confirm)
      if (confirm) {
        const res = await deleteRoleApi({ roleId: row.roleId })
        if (res && res.code === 200) {
          // 刷新表格
          this.getRoleList()
          // 删除成功提示
          this.$message.success(res.msg)
        }
      }
    },
    // 编辑按钮
    editBtn(row) {
      this.$resetForm('addForm', this.addModel)
      // 设置标识
      this.addModel.type = 1

      // 让表单数据回显道列表中
      this.$objCoppy(row, this.addModel)

      this.dialog.title = '编辑角色'
      // 关闭弹出框
      this.dialog.visible = true
    },
    // 新增或编辑确认事件
    onConfirm() {
      this.$refs.addForm.validate(async(valid) => {
        if (valid) {
          let res = null
          if (this.addModel.type === '0') {
            res = await addRoleApi(this.addModel)
          } else {
            res = await editRoleApi(this.addModel)
          }
          if (res && res.code === 200) {
            // 刷新表格
            this.getRoleList()
            this.$message.success(res.msg)
            this.dialog.visible = false
          }
        }
      })
    },
    // 弹框关闭事件
    onClose() {
      this.dialog.visible = false
    },
    // 页面内容改变时触发
    currentChange(val) {
      this.parms.currentPage = val
    },
    // 页面内容改变时触发
    sizeChange(val) {
      this.parms.pageSize = val
      this.getRoleList()
    },
    // 添加按钮
    addBtn() {
      // 清空表单数据
      this.$resetForm('addForm', this.addModel)
      // 设置新增或编辑状态
      this.addModel.type = '0'
      // 设置弹框属性
      this.dialog.title = '新增角色'
      this.dialog.visible = true
    },
    // 搜索按钮
    searchBtn(val) {
      this.getRoleList()
    },
    // 重置按钮
    resetBtn() {
      this.parms.roleName = ''
      this.getRoleList()
    },
    async getRoleList() {
      const res = await getRoleListApi(this.parms)
      console.log(res)
      if (res && res.code === 200) {
        this.roleList = res.extend.list.records
        this.parms.total = res.extend.list.total
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
